<template>

  <div id="myUpload" class="myUpload">
    <!-- header -->
    <yd-navbar slot="navbar" fixed>
      <router-link to="/user/manage" slot="left">
        <yd-navbar-back-icon></yd-navbar-back-icon>
      </router-link>
      <span slot="center" style="font-size:18px">文件上传</span>
    </yd-navbar>

    <!-- content -->
    <div class="content-myUpload" fixed>
      <yd-cell-group>
        <yd-cell-item>
          <span slot="left">上传轮播图</span>
        </yd-cell-item>
        <form enctype="multipart/form-data" style="padding:15px 0;">
          <input style="padding-left:15px;width:100%;" type="file" ref="pic" name="file" />
        </form>
      </yd-cell-group>
      <yd-button size="large" @click.native="upload" bgcolor="#2196f3" color="#fff">上传</yd-button>
      <br>
      <p>{{count}}</p>
      <button @click="increment">+1</button>
      <button @click="decrement">-1</button>
    </div>
  </div>
</template>

<script>
  import axios from '../../axios'
  import baseService from '../../axios/'
  export default {
    name: 'myUpload',
    data() {
      return {
        message: '上传文件',
        file: ''
      }
    },
    computed: {
      count() {
        return this.$store.store.state.count
      }
    },
    methods: {
      increment() {
        this.$store.store.commit('increment')
        // this.$store.store.state.count = 'sdasdas'
        console.log(this.$store)
      },
      decrement() {
        this.$store.store.commit('decrement')
      },
      upload: function () {
        let file = this.$refs.pic.files[0]
        let formData = new FormData()
        formData.append('file', file)
        //将上传的文件名作为key值，保存在全局；
        let myfileName = formData.get("file").name;
        let index = myfileName.lastIndexOf(".");
        myfileName = myfileName.substring(0, index);
        console.log(myfileName);

        baseService.post('/manage/product/upload.do', formData).then((res) => {
          if (res.data.status == 10 || res.data.status == 1) {
            this.$dialog.alert({
              mes: res.data.msg
            });
            this.$router.push({
              path: '/user/login'
            })
          }
          if (res.data.status == 0) {
            this.$dialog.alert({
              mes: "上传成功"
            })
            //动态map赋值将修改后的文件名，保存在全局；
            let newFileName = res.data.data.url;
            global.fileName[myfileName] = newFileName;
            console.log(global.fileName);
          }
        })
      }
    }
  }

</script>

<style>
  .myUpload .content-myUpload {
    position: fixed;
    padding-top: 15%;
    height: 100%;
    width: 100%;
    overflow-y: auto !important;
  }

</style>
